package com.alipay.rebate.shop.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QiniuUtil {

  private static final String accessKey  = "j6pkWkxY2wXKrWe6jkSDXjjcogzn8HKjdOfe1f3P";
  private static final String secretKey = "5hYrvdis1U8wLWAbTj5_fjYJogpnT-Pda1s3p83n";
  private static final String bucketName = "lottery";
  private static Gson gson = new Gson();
  private static Logger logger = LoggerFactory.getLogger(QiniuUtil.class);

  public static String getQiniuUploadToken(){
    Auth auth = Auth.create(accessKey, secretKey);
    String token = auth.uploadToken(bucketName);
    return token;
  }

  public static void uploadPictureToQiNui(String localFilePath){
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region0());
    UploadManager uploadManager = new UploadManager(cfg);
    //如果是Windows情况下，格式是 D:\\qiniu\\test.png
    // String localFilePath = "/home/qiniu/test.png";
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    String key = null;
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucketName);
    try {
      Response response = uploadManager.put(localFilePath, key, upToken);
      //解析上传成功的结果
      DefaultPutRet putRet = gson.fromJson(response.bodyString(), DefaultPutRet.class);
      logger.debug("key is : {}",putRet.key);
      logger.debug("hash is : {}",putRet.hash);
    } catch (QiniuException ex) {
      Response r = ex.response;
      logger.debug("QiniuException is : {}",r);
      System.err.println(r.toString());
      try {
        System.err.println(r.bodyString());
      } catch (QiniuException ex2) {
        //ignore
      }
    }
  }

  // 根据key删除七牛空间中的文件
  public static void deleteQiNuiPicture(String key){
    Configuration cfg = new Configuration(Region.region0());
    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
      bucketManager.delete(bucketName, key);
    } catch (QiniuException ex) {
      //如果遇到异常，说明删除失败
      logger.debug("ex.code is : {}",ex.code());
      logger.debug("ex.response.toString is : {}",ex.response.toString());
//      System.err.println(ex.code());
//      System.err.println(ex.response.toString());
    }
  }

  // 获取七牛云空间的所有文件
  public static void getFileList(){
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region0());

    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    //文件名前缀
    String prefix = "6d81800a19d8bc3eb387a7a4958ba61ea9d345d4";
    //每次迭代的长度限制，最大1000，推荐值 1000
    int limit = 1000;
    //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
    String delimiter = "";

    //列举空间文件列表
    BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucketName, prefix, limit, delimiter);
    int result = 0;
    while (fileListIterator.hasNext()) {
      //处理获取的file list结果
      FileInfo[] items = fileListIterator.next();
      logger.debug("items is : {}",items);

      for (FileInfo item : items) {
        logger.debug("item key is : {}",item.key);
        logger.debug("item hash is : {}",item.hash);
        logger.debug("item fsize is : {}",item.fsize);
        logger.debug("item mimeType is : {}",item.mimeType);
        logger.debug("item putTime is : {}",item.putTime);
        logger.debug("item endUser is : {}",item.endUser);
        result += 1;
        System.out.println();
      }
    }
    System.out.println(result);

  }

  public static void main(String[] args) {
    getFileList();
  }

}
